<template>
    <div class="file-list-container">
        <div class="header">
            <img :src="courseResourceInfo?.uploadUser?.avatarPath ? (baseUrl + courseResourceInfo?.uploadUser?.avatarPath ) : defaultAvatar()" alt="用户头像" class="user-avatar">
            <span class="username">{{ courseResourceInfo?.uploadUser?.userName }}</span>
            <a href="#" class="download-btn" v-if="courseResourceInfo?.fileList?.filter(file => file.selected).length > 0 || downloadFiles" @click.prevent="handleDownload">
                {{ downloadFiles ? '下载中...' : '下载' }}
            </a>
        </div>

        <div class="file-list">
            <div class="file-header">
                <input type="checkbox" class="file-checkbox" :checked="isAllSelected" @change="toggleSelectAll">
                <span>文件名</span>
                <span>文件类型</span>
                <span>文件大小</span>
                <span>上传时间</span>
            </div>
            <div v-for="file in courseResourceInfo?.fileList" :key="file.fileId" class="file-item">
                <div class="progress-bar" :class="{ 'progress-bar-active': file.progress > 0 }" v-if="file.progress != 0" :style="{width: file.progress === -1 ? '100%' : file.progress + '%'}"></div>
                <input type="checkbox" class="file-checkbox" v-model="file.selected">
                <div class="file-name">
                    <img :src="FileProcessing.getFileIcon(file.fileName)" alt="文件图标" class="file-icon">
                    {{ file.fileName }}
                </div>
                <span class="file-type">{{ file.contentType }}</span>
                <span class="file-size">{{ FileProcessing.getFileSize(file.fileSize) }}</span>
                <span class="file-time">{{ file.createDate }}</span>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { resourceApi } from '@/api/course/Course';
import { ref, defineComponent, computed, watch } from 'vue'
import { FileProcessing } from '@/util/file_processing';
import { userAvatar as defaultAvatar } from '@/types/Base64Image';
import { baseUrl } from '@/util/request';
import { userApi } from '@/api/Users';
import { CourseResource } from '@/types/Course';

export default defineComponent({
    name: 'CourseContentResource',
});
</script>

<script setup lang="ts">
    // 定义props
    const props = withDefaults(defineProps<{
        modelValue: number;
    }>(), {
        modelValue: 0
    });

    // 文件数据
    const courseResourceInfo = ref<CourseResource>(null);

    // 计算属性：是否全选
    const isAllSelected = computed(() => {
        return courseResourceInfo.value?.fileList?.length > 0 && courseResourceInfo.value?.fileList?.every(file => file.selected)
    })

    const toggleSelectAll = (event) => {
        const isChecked = event.target.checked
        courseResourceInfo.value?.fileList?.forEach(file => {
            file.selected = isChecked
        })
    }

    // 正在下载
    const downloadFiles = ref(false);

    const handleDownload = async () => {
        if (downloadFiles.value) return;
        const selectedFiles = courseResourceInfo.value?.fileList?.filter(file => file.selected)
        downloadFiles.value = true;
        selectedFiles.forEach(file => { file.progress = -1 });
        console.log('下载选中的文件：', selectedFiles)
        const user = await userApi.getLoginUserData();
        for (const file of selectedFiles) {
            resourceApi.files.download(file.fileId, file.fileName);
            while (true) {
                const progress = await resourceApi.files.getProgress("download_course_resource_" + user.userId + "_" + file.fileId);
                console.log("下载进度：" + progress)
                file.progress = progress;
                if (progress >= 100) {
                    break;
                }
                await new Promise(resolve => setTimeout(resolve, 1000));
            }
        }
        await new Promise(resolve => setTimeout(resolve, 1000));
        alert("下载完成");
        selectedFiles.forEach(file => { file.progress = 0 });
        downloadFiles.value = false;
    }
    
    watch(() => props.modelValue, async (newvValue) => {
        courseResourceInfo.value = await resourceApi.getResourceInfo(newvValue);
        console.log("文件列表更新了" + newvValue);
    },
    { immediate: true });
</script>

<style scoped>
.file-list-container {
    width: 100%;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
    padding: 20px;
}

.header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
}

.username {
    color: #333;
    font-size: 16px;
}

.download-btn {
    margin-left: auto;
    padding: 6px 20px;
    background-color: #fff;
    border: 1px solid #1890ff;
    color: #1890ff;
    border-radius: 4px;
    cursor: pointer;
    text-decoration: none;
}

.file-list {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.file-header {
    display: grid;
    grid-template-columns: 40px 1fr 300px 120px 150px;
    padding: 12px 20px;
    border-bottom: 1px solid #e8e8e8;
    color: #666;
}

.file-item {
    display: grid;
    grid-template-columns: 40px 1fr 300px 120px 150px;
    padding: 12px 20px;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;
    position: relative;
}

.progress-bar {
    position: absolute;
    border-radius: 5px;
    z-index: 0;
    top: 0;
    left: 0;
    height: 100%;
    background-color: rgba(255, 166, 0, .1);
}
.progress-bar.progress-bar-active {
    background-color: rgba(65, 185, 255, .2);
}

.file-item:last-child {
    border-bottom: none;
    position: relative;
}

.file-checkbox {
    width: 16px;
    height: 16px;
    position: relative;
}

.file-icon {
    width: 25px;
    height: 25px;
    margin-right: 8px;
    position: relative;
}

.file-name {
    display: flex;
    align-items: center;
    color: #333;
    position: relative;
}

.file-type,
.file-size,
.file-time {
    color: #666;
    position: relative;
}
</style>